import { Button, Card, Empty, Form, InputNumber, Select, Space, message } from 'antd'
import { useState, useEffect, useContext } from 'react'
import Player, { toText } from './Player';
import _ from 'lodash';
import { Feature } from 'ol';
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';
import CircleGeom from 'ol/geom/Circle';
import { fromCircle } from 'ol/geom/Polygon';
import useMap from '../../hooks/useMap';
import RiskReportContext from '../RiskReportContext';
import { lengthTo4326, wktToGeom } from '../../../../../../../utils/helper/mapHelper';
import CztApi from '../../../../../../../utils/apis/CztApi';
import LittleTitle from '../../../../../../common/LittleTitle';
export default function TimeAnalysis(props) {
    const map = useMap();
    const { zhData } = useContext(RiskReportContext);

    const [data, setData] = useState({
        kssc: null,
        ksscdw: 'h'
    });
    const [fxData, setFxData] = useState();

    const [loading, setLoading] = useState();
    const [fxResult, setFxResult] = useState();

    const [playerVisible, setPlayerVisible] = useState();
    const [currentCircle, setCurrentCircle] = useState();

    useEffect(() => {
        if (zhData?.geom && props.visible) {
            let scatterLayer = map?.getLayers()?.getArray()?.find(layer => {
                return layer.get('id') === 'scatter-layer'
            });
            if (!scatterLayer) {
                scatterLayer = new VectorLayer({
                    id: 'scatter-layer',
                    source: new VectorSource()
                });
                map.addLayer(scatterLayer)
            }
            const scatterSource = scatterLayer.getSource();

            const style = new Style({
                fill: new Fill({
                    color: 'rgba(255,0,0,0.3)'
                }),
                stroke: new Stroke({
                    color: 'rgba(255,0,0,1)',
                    width: 3
                })
            });
            const newCircle = new CircleGeom(wktToGeom(zhData.geom)?.getCoordinates(), lengthTo4326(1));
            const feature = new Feature({
                geometry: newCircle
            })
            feature.setStyle(style);
            scatterSource.addFeature(feature)
            setCurrentCircle(newCircle);
            return () => {
                scatterSource.clear()
                setCurrentCircle(null);
            }
        }

    }, [map, zhData, props.visible])

    let kssc = 0;
    if (fxData?.kssc) {
        switch (fxData?.ksscdw) {
            case 'm':
                kssc = fxData.kssc;
                break;
            case 'h':
                kssc = fxData.kssc * 60;
                break;
            case 'd':
                kssc = fxData.kssc * 60 * 24
                break;
            default:
        }
    }

    return <div className='layout-v h100' style={{
        overflow: 'auto'
    }}>
        {playerVisible && currentCircle && <Player dw={fxData?.ksscdw} kssc={kssc} currentCircle={currentCircle} radius={fxData?.yxbj} />}
        <div className='layout-h center' style={{
            // padding: "24px 0"
            paddingBottom: 12
        }}>
            <Space direction="vertical" style={{
                width: "100%"
            }} size={24}>
                <InputNumber addonBefore="扩散时长" value={data.kssc} onChange={value => {
                    setData(d => {
                        return {
                            ...d,
                            kssc: value
                        }
                    })
                }} addonAfter={<Select value={data.ksscdw} style={{
                    width: 70
                }} onChange={value => {
                    setData(d => {
                        return {
                            ...d,
                            ksscdw: value
                        }
                    })
                }} options={[{
                    label: '分钟',
                    value: 'm'
                }, {
                    label: '小时',
                    value: 'h'
                }, {
                    label: '天',
                    value: 'd'
                }]}></Select>} style={{
                    width: "100%"
                }} />
                <InputNumber style={{
                    width: "100%"
                }} addonBefore={"影响半径"} addonAfter={"米"} value={data.yxbj} onChange={value => {
                    setData(d => {
                        return {
                            ...d,
                            yxbj: value
                        }
                    })
                }} />
                <div style={{
                    textAlign: "right"
                }}>
                    <Button type="primary" loading={loading} disabled={!zhData} onClick={e => {
                        if (!data.yxbj) {
                            message.error('请输入影响半径');
                            return;
                        }
                        if (!data.kssc) {
                            message.error('请输入扩散时长');
                            return;
                        }
                        setPlayerVisible(true);
                        setFxData(data);
                        const point = wktToGeom(zhData.geom)?.getCoordinates()
                        // const [interval, newCircle] = animateScatter({
                        //     map,
                        //     point: wktToGeom(zhData.geom)?.getCoordinates(),
                        //     timeStep: 10,
                        //     radius: data.yxbj
                        // });

                        const maxCircle = new CircleGeom(point, lengthTo4326(data.yxbj));
                        maxCircle.scale(2)
                        // setCurrentCircle(newCircle)
                        // setTimeInterval(interval);
                        map.getView().fit(maxCircle, {
                            duration: 500
                        });
                        setLoading(true);
                        setTimeout(() => {
                            setLoading(false);
                        }, 10000);

                        const rs = [data.yxbj * 0.25, data.yxbj * 0.5, data.yxbj * 0.75, data.yxbj].map(radius => {
                            const circle = new CircleGeom(point, lengthTo4326(radius));
                            return CztApi.listByPolygon(fromCircle(circle))
                        });
                        const yxs = [];

                        let kssc = 0;
                        if (data?.kssc) {
                            switch (data?.ksscdw) {
                                case 'm':
                                    kssc = data.kssc;
                                    break;
                                case 'h':
                                    kssc = data.kssc * 60;
                                    break;
                                case 'd':
                                    kssc = data.kssc * 60 * 24
                                    break;
                                default:
                            }
                        }
                        Promise.all(rs).then(resps => {
                            resps.forEach((resp, i) => {
                                if (resp.data?.length > 0) {
                                    yxs.push({
                                        time: toText(data.kssc * ((i + 1) * 0.25), data.ksscdw, data.ksscdw),
                                        datas: resp.data
                                    })
                                }
                            });
                            setFxResult(yxs)
                        })

                    }}>开始分析</Button>
                </div>
            </Space>
        </div>
        <LittleTitle fontSize={16} icon={false}>分析结果</LittleTitle>
        <div>
            {(loading) ? <div>
                计算中...
            </div> : <div>
                {fxResult?.length > 0 ? fxResult.map(result => {
                    return <Card style={{
                        marginTop: 12
                    }} size='small' key={result.time} title={<div>{result.time}将影响到</div>}>
                        {/* <div>{result.time}将影响到</div> */}
                        <div>{result.datas.map(item => {
                            return <div key={item.name} className='layout-h center'>
                                <div>{item.name}</div>
                                <div style={{
                                    padding: "0 4px",
                                    fontWeight: "bold",
                                    color: "rgb(255,255,0)"
                                }}> {item.count} </div>
                                <div>处</div>
                            </div>
                        })}</div>
                    </Card>
                }) : <div className='layout-v center'>该范围内暂无数据</div>}
            </div>}
        </div>
    </div>
}